﻿using Autofac;
using Autofac.Integration.Mvc;
using BarManagement.ApplicationServices.Base;
using BarManagement.Bootstrapper;
using BarManagement.DomainModel.Base.Logging;
using BarManagement.DomainService.Base;
using BarManagement.Infrastructure.DataAccess;
using BarManagement.Infrastructure.DataAccess.Base;
using BarManagement.Infrastructure.DataAccess.Identity;
using BarManagement.Infrastructure.DataAccess.Orders;
using BarManagement.Infrastructure.Logging;
using BarManagement.UI.Web.Mvc;
using System.Web.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace BarManagement.Bootstrapper
{
    public class IocConfig
    {
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();
            
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterModule<AutofacWebTypesModule>();
            builder.RegisterGeneric(typeof(RepositoryBase<>)).As(typeof(IRepository<>)).InstancePerRequest();         
            builder.RegisterGeneric(typeof(ServiceBase<>)).As(typeof(IService<>)).InstancePerRequest();
            builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerRequest();
            
            //- Identity context
            builder.Register<IDataContext>(b =>
            {
                string nameOrConnectionString = "name=AppContext";
                var logger = b.Resolve<ILogger>();
                var context = new IdentityDataContext(nameOrConnectionString, logger);
                return context;
            }).InstancePerRequest();

            //- Orders context
            builder.Register<IDataContext>(b =>
            {
                string nameOrConnectionString = "name=AppContext";
                var logger = b.Resolve<ILogger>();
                var context = new OrdersContext(nameOrConnectionString, logger);
                return context;
            }).InstancePerRequest();
            
            builder.Register(b => NLogLogger.Instance).SingleInstance();
            builder.RegisterModule(new IdentityModule());

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}
